<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI模型API Key配置工具</title>
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
            line-height: 1.6;
            color: #333;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f7fa;
        }
        .container {
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
            padding: 30px;
            margin-bottom: 20px;
        }
        h1 {
            color: #409eff;
            margin-bottom: 20px;
            text-align: center;
        }
        h2 {
            color: #303133;
            margin-top: 30px;
            margin-bottom: 15px;
            font-size: 18px;
            border-bottom: 2px solid #ecf5ff;
            padding-bottom: 8px;
        }
        .model-card {
            border: 1px solid #ebeef5;
            border-radius: 6px;
            padding: 20px;
            margin-bottom: 20px;
            transition: all 0.3s ease;
        }
        .model-card:hover {
            border-color: #409eff;
            box-shadow: 0 0 10px rgba(64, 158, 255, 0.1);
        }
        .model-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
        }
        .model-name {
            font-weight: 500;
            font-size: 16px;
            color: #303133;
        }
        .default-badge {
            background-color: #e6f7ff;
            color: #1890ff;
            padding: 4px 12px;
            border-radius: 12px;
            font-size: 12px;
        }
        .form-group {
            margin-bottom: 15px;
        }
        label {
            display: block;
            margin-bottom: 5px;
            color: #606266;
            font-weight: 500;
        }
        input[type="text"], input[type="password"] {
            width: 100%;
            padding: 8px 12px;
            border: 1px solid #dcdfe6;
            border-radius: 4px;
            font-size: 14px;
            transition: border-color 0.3s;
            box-sizing: border-box;
        }
        input[type="text"]:focus, input[type="password"]:focus {
            outline: none;
            border-color: #409eff;
        }
        .btn {
            padding: 8px 20px;
            border: none;
            border-radius: 4px;
            font-size: 14px;
            cursor: pointer;
            transition: all 0.3s;
            margin-right: 10px;
            margin-bottom: 10px;
        }
        .btn-primary {
            background-color: #409eff;
            color: white;
        }
        .btn-primary:hover {
            background-color: #66b1ff;
        }
        .btn-default {
            background-color: #f0f2f5;
            color: #606266;
        }
        .btn-default:hover {
            background-color: #e6e8eb;
        }
        .btn-success {
            background-color: #67c23a;
            color: white;
        }
        .btn-success:hover {
            background-color: #85ce61;
        }
        .btn-danger {
            background-color: #f56c6c;
            color: white;
        }
        .btn-danger:hover {
            background-color: #f78989;
        }
        .status {
            margin-top: 15px;
            padding: 10px;
            border-radius: 4px;
            font-size: 14px;
        }
        .status-success {
            background-color: #f0f9eb;
            color: #67c23a;
            border: 1px solid #e1f3d8;
        }
        .status-error {
            background-color: #fef0f0;
            color: #f56c6c;
            border: 1px solid #fbc4c4;
        }
        .tips {
            background-color: #f0f9eb;
            color: #67c23a;
            padding: 12px;
            border-radius: 4px;
            margin-top: 20px;
            font-size: 14px;
            border-left: 4px solid #67c23a;
        }
        .code-block {
            background-color: #f8f8f8;
            padding: 15px;
            border-radius: 4px;
            border: 1px solid #eaeaea;
            font-family: 'Courier New', Courier, monospace;
            font-size: 13px;
            overflow-x: auto;
            margin: 10px 0;
        }
        .actions {
            margin-top: 20px;
            display: flex;
            flex-wrap: wrap;
        }
        .footer {
            text-align: center;
            color: #909399;
            font-size: 14px;
            margin-top: 30px;
        }
        .checkbox-group {
            display: flex;
            align-items: center;
            margin-top: 10px;
        }
        input[type="checkbox"] {
            margin-right: 8px;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>AI模型API Key配置工具</h1>
        
        <div id="status" class="status" style="display: none;"></div>
        
        <h2>当前配置信息</h2>
        <div id="current-config" class="code-block">加载中...</div>
        
        <div id="model-configs">
            <!-- 模型配置表单将通过JavaScript动态生成 -->
        </div>
        
        <div class="actions">
            <button id="save-all-btn" class="btn btn-primary">保存所有配置</button>
            <button id="reset-all-btn" class="btn btn-danger">重置所有配置</button>
            <button id="refresh-btn" class="btn btn-default">刷新配置</button>
        </div>
        
        <div class="tips">
            <strong>使用提示：</strong><br>
            1. 请为您需要使用的AI模型填写API Key<br>
            2. API Base URL通常使用默认值即可，如果有特殊要求可以修改<br>
            3. 配置完成后，刷新应用页面使配置生效<br>
            4. 配置信息将保存在浏览器的本地存储中，不会上传到服务器
        </div>
    </div>
    
    <div class="footer">
        <p>配置工具版本 1.0</p>
    </div>
    
    <script>
        // 模型类型和默认API Base URL映射
        const MODEL_INFO = {
            'deepseek-r1': { name: 'DeepSeek-R1', defaultApiBase: 'https://api.deepseek.com' },
            'doubao': { name: '豆包', defaultApiBase: 'https://api.doubao.com' },
            'tongyiqianwen': { name: '通义千问', defaultApiBase: 'https://api.tongyi.aliyun.com' },
            'chatgpt': { name: 'ChatGPT', defaultApiBase: 'https://api.openai.com' }
        };
        
        // 初始化页面
        document.addEventListener('DOMContentLoaded', function() {
            // 尝试获取配置管理器实例
            if (typeof window.aiModelConfig === 'undefined') {
                try {
                    // 尝试从localStorage直接读取配置
                    const savedConfig = localStorage.getItem('aiModelSettings');
                    if (savedConfig) {
                        loadConfigFromStorage(savedConfig);
                    } else {
                        showStatus('错误', '无法访问aiModelConfig，请在应用页面中打开此工具。', 'error');
                    }
                } catch (error) {
                    showStatus('错误', '无法加载配置: ' + error.message, 'error');
                }
            } else {
                loadAndRenderConfigs();
            }
            
            // 添加按钮事件监听器
            document.getElementById('save-all-btn').addEventListener('click', saveAllConfigs);
            document.getElementById('reset-all-btn').addEventListener('click', resetAllConfigs);
            document.getElementById('refresh-btn').addEventListener('click', loadAndRenderConfigs);
        });
        
        // 从aiModelConfig加载配置并渲染
        function loadAndRenderConfigs() {
            try {
                const config = window.aiModelConfig.getConfig();
                renderConfigs(config);
                showStatus('成功', '配置加载成功', 'success');
            } catch (error) {
                showStatus('错误', '加载配置失败: ' + error.message, 'error');
                console.error('加载配置失败:', error);
            }
        }
        
        // 从localStorage直接加载配置
        function loadConfigFromStorage(savedConfigStr) {
            try {
                const config = JSON.parse(savedConfigStr);
                renderConfigs(config);
                document.getElementById('save-all-btn').disabled = true;
                document.getElementById('save-all-btn').title = '请在应用页面中保存配置';
                showStatus('提示', '已从本地存储加载配置预览，但无法直接保存。请在应用页面中打开此工具进行保存操作。', 'success');
            } catch (error) {
                showStatus('错误', '解析配置失败: ' + error.message, 'error');
            }
        }
        
        // 渲染配置表单
        function renderConfigs(config) {
            const container = document.getElementById('model-configs');
            container.innerHTML = '';
            
            // 显示当前配置概览
            const configOverview = document.getElementById('current-config');
            configOverview.textContent = JSON.stringify(config, null, 2);
            
            // 为每个模型创建配置表单
            Object.keys(MODEL_INFO).forEach(modelType => {
                const modelInfo = MODEL_INFO[modelType];
                const isDefault = config.defaultModel === modelType;
                
                const card = document.createElement('div');
                card.className = 'model-card';
                
                card.innerHTML = `
                    <div class="model-header">
                        <span class="model-name">${modelInfo.name}</span>
                        ${isDefault ? '<span class="default-badge">默认模型</span>' : ''}
                    </div>
                    
                    <div class="form-group">
                        <label for="api-key-${modelType}">API Key</label>
                        <input type="password" id="api-key-${modelType}" placeholder="请输入API Key">
                    </div>
                    
                    <div class="form-group">
                        <label for="api-base-${modelType}">API Base URL</label>
                        <input type="text" id="api-base-${modelType}" value="${config.models?.[modelType]?.apiBase || modelInfo.defaultApiBase}" placeholder="API Base URL">
                    </div>
                    
                    <div class="checkbox-group">
                        <input type="checkbox" id="set-default-${modelType}" ${isDefault ? 'checked' : ''}>
                        <label for="set-default-${modelType}">设为默认模型</label>
                    </div>
                    
                    <div class="actions">
                        <button class="btn btn-primary save-model-btn" data-model="${modelType}">保存此模型</button>
                    </div>
                `;
                
                container.appendChild(card);
                
                // 设置API Key（如果已配置）
                const apiKeyInput = document.getElementById(`api-key-${modelType}`);
                if (config.models?.[modelType]?.apiKey) {
                    apiKeyInput.value = config.models[modelType].apiKey;
                }
                
                // 添加保存按钮事件
                const saveBtn = card.querySelector('.save-model-btn');
                saveBtn.addEventListener('click', function() {
                    saveModelConfig(modelType);
                });
            });
        }
        
        // 保存单个模型配置
        function saveModelConfig(modelType) {
            try {
                const apiKey = document.getElementById(`api-key-${modelType}`).value;
                const apiBase = document.getElementById(`api-base-${modelType}`).value;
                const setAsDefault = document.getElementById(`set-default-${modelType}`).checked;
                
                // 保存模型配置
                window.aiModelConfig.saveModelConfig(modelType, { apiKey, apiBase });
                
                // 如果需要设为默认模型
                if (setAsDefault) {
                    window.aiModelConfig.setDefaultModel(modelType);
                }
                
                showStatus('成功', `${MODEL_INFO[modelType].name} 配置保存成功`, 'success');
                
                // 重新加载配置以更新默认模型标记
                loadAndRenderConfigs();
            } catch (error) {
                showStatus('错误', `保存${MODEL_INFO[modelType].name}配置失败: ` + error.message, 'error');
            }
        }
        
        // 保存所有配置
        function saveAllConfigs() {
            try {
                let hasError = false;
                const errors = [];
                
                // 保存每个模型的配置
                Object.keys(MODEL_INFO).forEach(modelType => {
                    try {
                        const apiKey = document.getElementById(`api-key-${modelType}`).value;
                        const apiBase = document.getElementById(`api-base-${modelType}`).value;
                        const setAsDefault = document.getElementById(`set-default-${modelType}`).checked;
                        
                        // 保存模型配置
                        window.aiModelConfig.saveModelConfig(modelType, { apiKey, apiBase });
                        
                        // 如果需要设为默认模型
                        if (setAsDefault) {
                            window.aiModelConfig.setDefaultModel(modelType);
                        }
                    } catch (error) {
                        hasError = true;
                        errors.push(`${MODEL_INFO[modelType].name}: ${error.message}`);
                    }
                });
                
                if (hasError) {
                    showStatus('部分成功', '部分模型配置保存失败: ' + errors.join('; '), 'error');
                } else {
                    showStatus('成功', '所有模型配置保存成功', 'success');
                }
                
                // 重新加载配置
                loadAndRenderConfigs();
            } catch (error) {
                showStatus('错误', '保存所有配置失败: ' + error.message, 'error');
            }
        }
        
        // 重置所有配置
        function resetAllConfigs() {
            if (confirm('确定要重置所有AI模型配置吗？这将清除所有已保存的API Key。')) {
                try {
                    window.aiModelConfig.resetConfig();
                    showStatus('成功', '所有配置已重置为默认值', 'success');
                    loadAndRenderConfigs();
                } catch (error) {
                    showStatus('错误', '重置配置失败: ' + error.message, 'error');
                }
            }
        }
        
        // 显示状态消息
        function showStatus(title, message, type) {
            const statusEl = document.getElementById('status');
            statusEl.textContent = `${title}: ${message}`;
            statusEl.className = 'status ' + (type === 'error' ? 'status-error' : 'status-success');
            statusEl.style.display = 'block';
            
            // 3秒后自动隐藏成功消息
            if (type !== 'error') {
                setTimeout(() => {
                    statusEl.style.display = 'none';
                }, 3000);
            }
        }
    </script>
</body>
</html>